import React, { Component } from 'react';
import { Carousel, Flex, Modal, Toast } from 'antd-mobile';
import { BASE_URL } from '../../utils/url.js';
import styles from './index.module.scss'
import MyNavBar from '../../components/MyNavBar'
import classnames from 'classnames'
import HouseMatch from '../../components/HouseMatch';
import HouseItem from '../../components/HouseItem'
import { isAuth } from '../../utils/token';
const BMap = window.BMap
const labelStyle = {
    position: "absolute",
    zIndex: -1,
    backgroundColor: "rgb(238, 93, 91)",
    color: "rgb(255, 255, 255)",
    height: 25,
    padding: "5px 10px",
    lineHeight: "14px",
    borderRadius: 3,
    boxShadow: "rgb(204, 204, 204) 2px 2px 2px",
    whiteSpace: "nowrap",
    fontSize: 12,
    userSelect: "none",
};
// 猜你喜欢
const recommendHouses = [
    {
        id: 1,
        houseCode: '5cc477061439630e5b467b0b',
        houseImg: '/newImg/7bk83o0cf.jpg',
        desc: '72.32㎡/南 北/低楼层',
        title: '安贞西里 3室1厅',
        price: 4500,
        tags: ['随时看房']
    },
    {
        id: 2,
        houseCode: '5cc4a1dd1439630e5b502266',
        houseImg: '/newImg/7bk83o0cf.jpg',
        desc: '83㎡/南/高楼层',
        title: '天居园 2室1厅',
        price: 7200,
        tags: ['近地铁']
    },
    {
        id: 3,
        houseCode: '5cc46a921439630e5b439611',
        houseImg: '/newImg/7bk83o0cf.jpg',
        desc: '52㎡/西南/低楼层',
        title: '角门甲4号院 1室1厅',
        price: 4300,
        tags: ['集中供暖']
    }
]
class Detail extends Component {
    constructor() {
        super()
        this.state = {
            houseInfo: null,
            imgHeight: 252,
            isFavorite: false
        }
    }
    componentDidMount() {
        // 获取房源信息
        this.getSideshow()
        // 获取房屋收藏状态
        this.getHouseFavorite()
    }

    // 获取房屋收藏状态
    getHouseFavorite = async () => {
        let res = await this.axios.get(`/user/favorites/${this.props.match.params.id}`)
        console.log(res, "房屋的收藏状态")
        if (res.data.status == 200) {
            this.setState({
                isFavorite: res.data.body.isFavorite
            })
        } else {
        }
    }
    // 获取房源轮播图数据
    getSideshow = async () => {
        const res = await this.axios.get(`/houses/${this.props.match.params.id}`)
        this.setState({
            houseInfo: res.data.body
        }, () => {
            console.log(this.state.houseInfo, "houseInfo")
            this.initMap()
        })
    }
    // 渲染轮播图
    renderSideshow = () => {
        return (
            <Carousel
                autoplay
                className={styles.slides}
                infinite
            >
                {this.state.houseInfo.houseImg.map(item => (
                    <a
                        key={item}
                        href="http://www.alipay.com"
                        style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                    >
                        <img
                            src={`${BASE_URL}${item}`}
                            alt=""
                            style={{ width: '100%', height: '100%', verticalAlign: 'top' }}
                            onLoad={() => {
                                // fire window resize event to change height
                                window.dispatchEvent(new Event('resize'));
                                this.setState({ imgHeight: 252 });
                            }}
                        />
                    </a>
                ))}
            </Carousel>
        )
    }
    // 渲染房源基本信息
    renderBaseInfo = () => {
        const { houseInfo } = this.state
        return (
            <div className={styles.info}>
                <h3 className={styles.title}>{houseInfo.title}</h3>
                <Flex className={styles.tags}>
                    {houseInfo.tags.map((item, index) => {
                        const tagName = `tag${index % 3 + 1}`
                        return (
                            <span key={item} className={classnames(styles.tag, styles[tagName])}>
                                {item}
                            </span>
                        )
                    })}
                </Flex>
                <Flex className={styles.infoPrice}>
                    <Flex.Item className={styles.infoPriceItem}>
                        <div>
                            {houseInfo.price}
                            <span className={styles.month}>月</span>
                        </div>
                        <div>
                            租金
                        </div>
                    </Flex.Item>
                    <Flex.Item className={styles.infoPriceItem}>
                        <div>
                            {houseInfo.roomType}
                        </div>
                        <div>
                            房型
                        </div>
                    </Flex.Item>
                    <Flex.Item className={styles.infoPriceItem}>
                        <div>
                            {houseInfo.size}
                        </div>
                        <div>
                            面积
                        </div>
                    </Flex.Item>
                </Flex>
                <Flex className={styles.infoBasic} align="center">
                    <Flex.Item>
                        <div>
                            <span className={styles.title}>装修 : </span>
                            精装修
                        </div>
                        <div>
                            <span className={styles.title}>楼层 : </span>
                            {houseInfo.floor}
                        </div>
                    </Flex.Item>
                    <Flex.Item>
                        <div>
                            <span className={styles.title}>朝向 : </span>
                            {houseInfo && houseInfo.oriented.join(" ")}
                        </div>
                        <div>
                            <span className={styles.title}>类型 : </span>
                            普通住宅
                        </div>
                    </Flex.Item>
                </Flex>
            </div>
        )
    }
    // 渲染小区地图
    renderMap = () => {
        const { houseInfo: { community } } = this.state
        return (
            <div className={styles.map}>
                <div className={styles.mapTitle}>
                    小区 : <span>{community}</span>
                </div>
                <div className={styles.mapContainer} id="map"></div>
            </div>
        )
    }
    // 初始化地图及覆盖物
    initMap = () => {
        const { houseInfo: { coord: { longitude, latitude }, community } } = this.state;
        console.log(longitude, "longitude")
        console.log(latitude, "latitude")
        // 创建地图实例
        const map = new BMap.Map("map")

        // 设置中心点或经纬度
        var point = new BMap.Point(longitude, latitude);
        map.centerAndZoom(point, 15);

        // 覆盖物
        var opts = {
            position: point, // 指定文本标注所在的地理位置
            offset: new BMap.Size(-65, -10) // 设置文本偏移量
        }
        var label = new BMap.Label("", opts); // 创建文本标注对象
        label.setStyle(labelStyle);
        label.setContent(`
            <div>${community}</div>
            <div class=${styles.mapArrow}></div>
        `);
        map.addOverlay(label)
    }
    // 渲染房屋配置
    renderHouseMatch = () => {
        const { houseInfo: { supporting } } = this.state
        return (
            <div className={styles.about}>
                <div className={styles.houseTitle}>房屋配套</div>
                <div>
                    {supporting.length > 0 ? (
                        <HouseMatch data={supporting} />
                    ) : ("暂无数据")}
                </div>
            </div>
        )
    }
    // 渲染房屋描述
    renderHouseDesc = () => {
        const { houseInfo: { description } } = this.state
        return (
            <div className={styles.set}>
                <div>
                    <div className={styles.contact}>
                        <div className={styles.user}>
                            <img src="http://huangjiangjun.top:8088/img/avatar.png" alt="" />
                            <div className={styles.userInfo}>
                                <div>王女士</div>
                                <div className={styles.userAuth}>
                                    <i className="iconfont icon-auth"></i>
                                    已认证房主
                                </div>
                            </div>
                        </div>
                        <div className={styles.userMsg}>发消息</div>
                    </div>
                </div>
                <div className={styles.descText}>
                    {description.length > 0 ?
                        description : "暂无描述"
                    }
                </div>
            </div>
        )
    }
    // 渲染推荐房源
    renderRecommend = () => {
        return (
            <div className={styles.recommend}>
                <div className={styles.houseTitle}>猜你喜欢</div>
                <div className={styles.items}>
                    {
                        recommendHouses.map(item => {
                            return <HouseItem key={item.houseCode} {...item} />
                        })
                    }
                </div>
            </div>
        )
    }
    // 收藏或者取消收藏
    favoriteOrNot = async () => {
        let Auth = isAuth()
        console.log('====================================');
        console.log(isAuth, "isAuth");
        console.log('====================================');
        // 未登录
        if (!Auth) {
            Modal.alert('提示', '登录后才能收藏房源，是否去登录?', [
                { text: '取消', onPress: () => console.log('cancel') },
                {
                    text: '去登录',
                    onPress: () =>
                        this.props.history.push('/login')
                }
            ])
            return
        }
        // 之前收藏过
        if (this.state.isFavorite) {
            const res = await this.axios.delete(`/user/favorites/${this.props.match.params.id}`)
            if (res.data.status == 200) {
                Toast.info("取消成功", 1.5)
                this.setState({
                    isFavorite: false
                })
            }

        } else {//之前收藏过 现在要收藏
            const res = await this.axios.post(`/user/favorites/${this.props.match.params.id}`)
            if (res.data.status == 200) {
                Toast.info("收藏成功", 1.5)
                this.setState({
                    isFavorite: true
                })
            }
        }
    }
    // 渲染底部
    renderFooter = () => {
        const { isFavorite } = this.state
        return (
            <Flex className={styles.fixedBottom} align="center">
                <Flex.Item onClick={this.favoriteOrNot}>
                    <img style={{ height: 16 }} className={styles.favoriteImg} src={isFavorite ? "http://huangjiangjun.top:8088/img/star.png" : "http://huangjiangjun.top:8088/img/unstar.png"} alt="" />
                    <span className={styles.favorite}>{isFavorite ? "已收藏" : "收藏"}</span>
                </Flex.Item>
                <Flex.Item>
                    在线咨询
                </Flex.Item>
                <Flex.Item>
                    <a className={styles.telephone} href="tel:4001234567">电话预约</a>
                </Flex.Item>
            </Flex>
        )
    }
    render() {
        const { houseInfo } = this.state
        return (
            <div className={styles.root}>
                <MyNavBar
                    className={styles.detailHeader}
                    title={houseInfo != null ? houseInfo.community : "加载中..."}
                    rightContent={[<i className="iconfont icon-share" />]}
                />
                {houseInfo && this.renderSideshow()}
                {houseInfo && this.renderBaseInfo()}
                {houseInfo && this.renderMap()}
                {houseInfo && this.renderHouseMatch()}
                {houseInfo && this.renderHouseDesc()}
                {houseInfo && this.renderRecommend()}
                {houseInfo && this.renderFooter()}
            </div>
        );
    }
}

export default Detail;